package com.hbgjq.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbgjq.security.config.MyGrantedAuthority;
import com.hbgjq.security.mapper.UserMapper;
import com.hbgjq.security.po.UserPo;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :Gjq
 * @date :2021/1/6
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {
    /**
     * 用户的mapper
     */
    @Resource
    private UserMapper userMapper;

    /**
     * 重写此方法 进行数据库的认证逻辑
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserPo userPo = userMapper.selectOne(new QueryWrapper<UserPo>().lambda().eq(UserPo::getUsername, s));
        if (userPo == null ) throw new UsernameNotFoundException("user is not exits");
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new MyGrantedAuthority("USER", "USER"));
        list.add(new MyGrantedAuthority("USER", "ROLE_USER"));
        userPo.setMyGrantedAuthorities(list);
        return userPo;
    }

    /**
     * 创建密码策略 不配置的话会报错 因为security从5.x开始 开启了强密码策略
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
